package com.nlecloud.bc.controller;

import com.nlecloud.bc.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author warrior
 * @description 文件上传操作API
 */
@RestController
@Slf4j
public class FileUploadController {

    private static final String BASE_FOLDER = "/uploadFile/";

    @Value("${file-save-path}")
    private String fileSavePath;

    /**
     * 上传文件
     *
     * @param uploadFile
     * @param req
     * @return
     */
    @PostMapping("file/upload")
    public Result uploadFile(MultipartFile uploadFile, HttpServletRequest req) {
        //指定文件存储位置
        File folder = new File(fileSavePath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + BASE_FOLDER + newName;
            return Result.succeed(filePath, "上传文件成功");
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.failed("上传失败! ");
        }
    }
}
